package com.yuncheng.spcyApi.busService;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.bo.JcyjParamBo;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.other.YwlxmbConstant;
import com.yuncheng.spcyApi.entity.SpcyFgFgmc;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.entity.SpcySqsxYwlxmb;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxYwlxmbService;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.Result;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Component(value = "ywlxmbService")
public class YwlxmbService {
    private static final Logger log = LoggerFactory.getLogger(YwlxmbService.class);

    @Resource
    @Lazy
    private ISpcySqsxYwlxmbService spcySqsxYwlxmbService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    // 模板分页查询
    public HttpResult queryPage(SpcySqsxYwlxmb ywlxmb, SpcySqsxBasic sqsx, Integer pageNo, Integer pageSize){
        Page<SpcySqsxYwlxmb> page = new Page<>(pageNo,pageSize);

        LambdaQueryWrapper<SpcySqsxYwlxmb> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(ywlxmb.getFmblx()), SpcySqsxYwlxmb::getFmblx, ywlxmb.getFmblx());

        if (sqsx != null && StringUtils.isNotBlank(sqsx.getFywflcode())){
            queryWrapper.eq(SpcySqsxYwlxmb::getFmbly, sqsx.getFywflcode());
        }

        if (StringUtils.isNotBlank(ywlxmb.getFmbly())){
            // 查询个人
            if (ywlxmb.getFmbly().equals(YwlxmbConstant.MBLY_GR)){
                queryWrapper.like(SpcySqsxYwlxmb::getFcjrid, GetCurrentUserUtils.getCurrentUserId());
            }

            if (ywlxmb.getFmbly().equals(YwlxmbConstant.MBLY_SPZX)){
                // 查询中心
                queryWrapper.notLike(SpcySqsxYwlxmb::getFcjrid, SpcyConstant.HCY_ORGNAME);
                queryWrapper.notLike(SpcySqsxYwlxmb::getFcjrid, GetCurrentUserUtils.getCurrentUserId());
            }

            if (ywlxmb.getFmbly().equals(YwlxmbConstant.MBLY_QT)){
                // 查询所有检查员
                queryWrapper.notLike(SpcySqsxYwlxmb::getFcjrid, GetCurrentUserUtils.getCurrentUserId());
            }
        }

        queryWrapper.like(StringUtils.isNotBlank(ywlxmb.getFmbnr()), SpcySqsxYwlxmb::getFmbnr, ywlxmb.getFmbnr());
        queryWrapper.orderByDesc(SpcySqsxYwlxmb::getFdycs);
        queryWrapper.orderByDesc(SpcySqsxYwlxmb::getCreateTime);
        IPage<SpcySqsxYwlxmb> pageList = spcySqsxYwlxmbService.page(page, queryWrapper);

        return HttpResult.ok(pageList);
    }

    // 选择模板
    public String selectMb(String id){
        SpcySqsxYwlxmb mb = spcySqsxYwlxmbService.getById(id);
        if (mb == null){
            throw new BusinessException("当前模板数据不存在！");
        }

        Integer fdycs = mb.getFdycs();
        mb.setFdycs(fdycs+1);
        spcySqsxYwlxmbService.updateById(mb);

        return mb.getFmbnr();
    }

    private List<SpcySqsxYwlxmb> queryList(SpcySqsxYwlxmb ywlxmb){
        LambdaQueryWrapper<SpcySqsxYwlxmb> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(ywlxmb.getFmblx()), SpcySqsxYwlxmb::getFmblx, ywlxmb.getFmblx());
        queryWrapper.eq(StringUtils.isNotBlank(ywlxmb.getFmbly()), SpcySqsxYwlxmb::getFmbly, ywlxmb.getFmbly());
        queryWrapper.like(StringUtils.isNotBlank(ywlxmb.getFmbnr()), SpcySqsxYwlxmb::getFmbnr, ywlxmb.getFmbnr());
        queryWrapper.like(StringUtils.isNotBlank(ywlxmb.getFcjrid()), SpcySqsxYwlxmb::getFcjrid, ywlxmb.getFcjrid());

        List<SpcySqsxYwlxmb> list = spcySqsxYwlxmbService.list(queryWrapper);

        return list;
    }

    /**
     * 获取检查依据
     * @return
     * [{id: content: }]
     */
    public List<Map> queryJcyj(SpcySqsxBasic sqsx,String sqsxid, String fmbnr){
        String fywflcode = "";
        if (sqsx != null && StringUtils.isNotBlank(sqsx.getFywflcode())){
            fywflcode = sqsx.getFywflcode();
        }

        // 根据模板类型、模板来源、模板内容查询
        List<SpcySqsxYwlxmb> mbList = this.queryList(new SpcySqsxYwlxmb(YwlxmbConstant.MBLX_JCYJ, fywflcode, fmbnr));
        List<Map> mapList = new ArrayList<>();
        Map dataMap = null;
        if (CollectionUtil.isNotEmpty(mbList)){
            for (SpcySqsxYwlxmb d : mbList){
                dataMap = new HashMap();
                dataMap.put("id", d.getId());
                dataMap.put("fmbnr", d.getFmbnr());
                mapList.add(dataMap);
            }
        }

        return mapList;
    }

    /**
     * 新增检查依据类型模板(检查依据)
     * @param fmbnr 模板内容
     * @param fywflcode 模板来源
     * @param sqsxid 申请事项id
     */
    public void addJcyjMbByJcyj(String fmbnr,String fywflcode,String sqsxid){
        this.addYwlxmb(YwlxmbConstant.MBLX_JCYJ, fmbnr, fywflcode, sqsxid);
    }

    /**
     * 新增检查依据类型模板(检查情况专述)
     * @param fmbnr 模板内容
     * @param fywflcode 模板来源
     * @param sqsxid 申请事项id
     */
    public void addJcyjMbByJcqkzs(String fmbnr,String fywflcode,String sqsxid){
        this.addYwlxmb(YwlxmbConstant.MBLX_JCQKZS, fmbnr, fywflcode, sqsxid);
    }

    /**
     * 新增检查依据类型模板(检查报告)
     * @param fmbnr 模板内容
     * @param fywflcode 模板来源
     * @param sqsxid 申请事项id
     */
    public void addJcyjMbByJcbg(String fmbnr,String fywflcode,String sqsxid){
        this.addYwlxmb(YwlxmbConstant.MBLX_JCBG, fmbnr, fywflcode, sqsxid);
    }

    /**
     * 新增检查依据类型模板(缺陷报告)
     * @param fmbnr 模板内容
     * @param fywflcode 模板来源
     * @param sqsxid 申请事项id
     */
    public void addJcyjMbByQxbg(String fmbnr,String fywflcode,String sqsxid){
        this.addYwlxmb(YwlxmbConstant.MBLX_QXBG, fmbnr, fywflcode, sqsxid);
    }

    /**
     * 新增业务功能模板
     * @param fmblx
     * @param fmbnr
     * @param fmbly
     * @param pid
     */
    public void addYwlxmb(String fmblx, String fmbnr, String fmbly, String pid){
        SpcySqsxYwlxmb ywlxmb = new SpcySqsxYwlxmb();
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        ywlxmb.setId(GetUuIdUtils.ReplaceUuId());
        ywlxmb.setFcjrid(currentUser.getId()+"/"+currentUser.getDeptName());
        ywlxmb.setFmblx(fmblx);
        ywlxmb.setFmbly(fmbly);
        ywlxmb.setFmbnr(fmbnr);
        ywlxmb.setFdycs(0);
        spcySqsxYwlxmbService.save(ywlxmb);

        StringBuffer lognr = new StringBuffer("新增");
        lognr.append("[").append(fmblx).append("]业务模板: ");
        if (StringUtils.isBlank(pid)){
            pid = ywlxmb.getId();
        }
        spcyLogService.addLogs(LogConstant.LOGS_YWGNMB,lognr.toString(), pid, LogConstant.LOGS_YWGNMB,SpcyConstant.LOGS_SYS_TYPE_XZ);
    }

    /**
     * 删除业务功能模板
     */
    public void deleteYwlxmb(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("删除失败，请求参数为空！");
        }
        SpcySqsxYwlxmb bean = spcySqsxYwlxmbService.getById(id);
        if (bean == null){
            throw new BusinessException("删除失败，当前数据不存在！");
        }

        if (!bean.getFcjrid().contains(GetCurrentUserUtils.getCurrentUserId())) {
            throw new BusinessException("当前模板无权限删除！只能删除个人的模板数据！");
        }

        spcySqsxYwlxmbService.removeById(id);

        StringBuffer lognr = new StringBuffer("删除");
        lognr.append("[").append(bean.getFmblx()).append("]业务模板: ");
        lognr.append(LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(bean)));

        spcyLogService.addLogs(LogConstant.LOGS_YWGNMB,lognr.toString(), id, LogConstant.LOGS_YWGNMB,SpcyConstant.LOGS_SYS_TYPE_SC);
    }

    /**
     * 保存模板
     */
    public void addCommonMb(JcyjParamBo paramBo, String fmblx){
        SpcySqsxYwlxmb ywlxmb = new SpcySqsxYwlxmb();
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        ywlxmb.setId(GetUuIdUtils.ReplaceUuId());
        ywlxmb.setFcjrid(currentUser.getId());
        ywlxmb.setFmblx(Optional.ofNullable(fmblx).orElseGet(()->YwlxmbConstant.MBLX_XCJCMB));
        ywlxmb.setFmbbt(Optional.ofNullable(paramBo.getFmbbt()).orElseGet(()->YwlxmbConstant.MBLX_XCJCMB));
        ywlxmb.setFmbly(Optional.ofNullable(paramBo.getFmbly()).orElseGet(()->YwlxmbConstant.MBLY_GR));
        ywlxmb.setFmbnr(paramBo.getFmbnr());
        ywlxmb.setFdycs(0);
        spcySqsxYwlxmbService.save(ywlxmb);

        StringBuffer lognr = new StringBuffer("新增个人模板：");
        spcyLogService.addLogs(LogConstant.LOGS_YWGNMB, lognr.toString(), ywlxmb.getFmblx(), "新增个人模板",SpcyConstant.LOGS_SYS_TYPE_XZ);

    }

    /**
     * 更新模板
     * @param map
     */
    public Result updateCommonMb(HashMap<String,Object> map){
        String id = "";
        try {
            id = map.get("id").toString();
        }catch (Exception e){
            return Result.error("参数为空！");
        }

        SpcySqsxYwlxmb update = spcySqsxYwlxmbService.getById(id);
        if (update == null){
            return Result.error("没有相匹配的数据！");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        try {
            BeanUtils.populate(update, map);
        } catch (IllegalAccessException e) {
            log.error("更新法律法规法规名称出错：【IllegalAccessException】-> {}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("更新法律法规法规名称出错：【InvocationTargetException】-> {}",e.getMessage());
        }

        spcySqsxYwlxmbService.updateById(update);

        String logNr = "更新个人模板: ";
        logNr += LogUtils.BeanModifyMsg(update, map);

        spcyLogService.addLogs(LogConstant.LOGS_FLFG_GL, logNr, update.getFmblx(),"更新个人模板", SpcyConstant.LOGS_SYS_TYPE_XG);

        return Result.ok();
    }

    public List<SpcySqsxYwlxmb> selectCommonMbList(String fmblx, String userid){
        return spcySqsxYwlxmbService.list(new LambdaQueryWrapper<SpcySqsxYwlxmb>()
                .eq(SpcySqsxYwlxmb::getFcjrid, userid)
                .eq(SpcySqsxYwlxmb::getFmblx, fmblx)
                .orderByDesc(SpcySqsxYwlxmb::getCreateTime));
    }
}
